package com.weme.common.util

import android.app.Activity
import android.view.View

class KeyboardVisibilityListener(activity: Activity) {

    private var isKeyboardVisible = false
    private val listeners = mutableListOf<KeyboardVisibilityListenerCallback>()

    init {
        val rootView = activity.window.decorView.findViewById<View>(android.R.id.content)

        val viewTreeObserver = rootView.viewTreeObserver
        viewTreeObserver.addOnGlobalLayoutListener {
            val rect = android.graphics.Rect()
            rootView.getWindowVisibleDisplayFrame(rect)
            val screenHeight = rootView.height

            // 计算差值，用于判断软键盘是否显示
            val keypadHeight = screenHeight - rect.height()

            // 根据差值来判断软键盘的显示状态
            if (keypadHeight > screenHeight * 0.15) {
                if (!isKeyboardVisible) {
                    isKeyboardVisible = true
                    notifyListeners(true,keypadHeight)
                }
            } else {
                if (isKeyboardVisible) {
                    isKeyboardVisible = false
                    notifyListeners(false,0)
                }
            }
        }
    }

    fun addVisibilityListener(listener: KeyboardVisibilityListenerCallback) {
        listeners.add(listener)
    }

    fun removeVisibilityListener(listener: KeyboardVisibilityListenerCallback) {
        listeners.remove(listener)
    }

    private fun notifyListeners(isVisible: Boolean, keyboardHeight: Int) {
        listeners.forEach { it.onKeyboardVisibilityChanged(isVisible, keyboardHeight) }
    }
}

interface KeyboardVisibilityListenerCallback {
    fun onKeyboardVisibilityChanged(isVisible: Boolean, keyboardHeight: Int)
}